package io.jee.runshan.controller;

import io.jee.runshan.domain.Member;
import io.jee.runshan.service.IMemberService;
import io.jee.runshan.utils.PasswordEncoder;
import io.jee.runshan.utils.StringUtils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {
	@Resource
	private IMemberService memberService;

	@RequestMapping("/login")
	public String login(Model model, HttpSession session, String username, String password, String valiCode) {
		Member member = (Member) session.getAttribute("CURRENT_LOGINED_MEMBER");
		if (member != null) {
			return "redirect:index";
		}
		model.addAttribute("username", username);
		member = memberService.unique("account", username);

		if (StringUtils.hasBlank(username, password, valiCode)) {
			model.addAttribute("message", "请填写完整信息进行登录");
			return "login";
		}
		
		String rand = (String) session.getAttribute("rand");
		if (!rand.equals(valiCode)) {
			model.addAttribute("message", "验证码错误");
			return "login";
		}
		
		if (member == null) {
			model.addAttribute("message", "用户不存在");
			return "login";
		}
		
		String emPassword = PasswordEncoder.encode(password, member.getSalt());
		if (!emPassword.equals(member.getPassword())) {
			model.addAttribute("message", "用户名或密码错误");
			return "login";
		}
		session.setAttribute("CURRENT_LOGINED_MEMBER", member);
		return "redirect:index";
	}

	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:index";
	}
	
	@RequestMapping("/admin/member/editPassword")
	public ModelAndView editPassword(){
		return new ModelAndView("admin/member/editPassword");
	}
	
	@RequestMapping("/admin/member/savePassword")
	public ModelAndView savePassword(HttpSession session,String oldPassword,String newPassword){
		String msg = null;
		try {
			Member member = (Member) session.getAttribute("CURRENT_LOGINED_MEMBER");
			if (member == null) {
				return new ModelAndView("redirect:login");
			}
			member = memberService.unique("account", member.getAccount());
			String emPassword = PasswordEncoder.encode(oldPassword, member.getSalt());
			if (!emPassword.equals(member.getPassword())) {
				msg = "原密码错误";
			}else{
				String newEmPassword = PasswordEncoder.encode(newPassword, member.getSalt());
				memberService.update("password", newEmPassword, member.getUid());
				msg = "密码修改成功，请重新登录";
				session.invalidate();
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = "未知错误：" + e.getMessage();
		}
		return new ModelAndView("admin/member/editPassword")
					.addObject("msg",msg)
					.addObject("oldPassword",oldPassword)
					.addObject("newPassword",newPassword);
	}

	@RequestMapping("/valiCode")
	public void valiCode(HttpServletResponse response, HttpSession session) throws Exception {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		int width = 85, height = 35;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = image.createGraphics();
		Random random = new Random();
		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);
		g.setFont(new Font("Times New Roman", Font.PLAIN, 32));
		g.setColor(getRandColor(160, 200));
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}
		String sRand = "";
		for (int i = 0; i < 4; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
			g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(rand, 20 * i + 6, 28);
		}
		session.setAttribute("rand", sRand);
		g.dispose();
		ImageIO.write(image, "JPEG", response.getOutputStream());
	}

	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255) fc = 255;
		if (bc > 255) bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

}
